<!doctype html>
<html>

<head>
    <meta charset=utf-8>
    <link rel="icon shortcut" href=img/logo.png type=image/png>
    <link rel=apple-touch-icon href=img/logo.png>
    <link rel=stylesheet href=lib/bootstrap-4.0.0-dist/css/bootstrap.min.css>
    <link rel=stylesheet href=css/base.css>
    <link rel=stylesheet href=css/ui-block.css>
    <meta name=viewport content="width=device-width">
    <title>NEBULAS</title>
    <style>
        .check_list {
            width: 400px;
            height: 500px;
            background-color: #f5f5f5;
            position: absolute;
            margin-left: 30%;
            margin-top: -50%;
            border-radius: 50px;
            padding: 20px;
        }

        .check_list .data {
            width: 100%;
        }

        .check_list .check {
            margin-top: 60px;
        }

        .active1 {
            display: none;
        }

        .transaction {
            margin-top: 1rem;
            display: none;
        }
    </style>
</head>

<body>
    <div class=logo-main></div>
    <div class=header></div>
    <div class="container select-wallet-file"></div>

    <div id=send class="container send">
        <div class="form-group row">
            <div class=col-md-6>
                <label data-i18n=send-nas/from-address>From Address</label>
                <div class="from icon-address" data-disabled></div>
            </div>
            <div class=col-md-6>
                <label data-i18n=send-nas/balance>Balance</label>
                <div class=number-comma data-disabled data-id=balance data-unit=currency data-currency-selector></div>
            </div>
        </div>
        <div class="form-group row">
            <div class=col>
                <label data-i18n=send-nas/to-address>To Address</label>
                <div class="icon-address to"></div>
            </div>
            <div class=col>
                <label for=amount data-i18n=send-nas/amount>Value / Amount to Send</label>
                <div class=number-comma data-data-i18n=amount data-id=amount data-unit=currency data-validate="required number eqgt0"></div>
            </div>
        </div>
        <div class="form-group row">
            <div class=col>
                <label for=limit>
                    <span data-i18n=gas-limit>Gas Limit</span>
                </label>
                <div class=number-comma data-data-i18n=amount data-id=limit data-validate="required number gt0" data-value=200000></div>
            </div>
            <div class=col>
                <label for=price>
                    <span data-i18n=gas-price>Gas Price</span>
                    <i>( 1 NAS = 1EWei = 10
                        <sup>18</sup> Wei )</i>
                </label>
                <div class=number-comma data-data-i18n=amount data-id=price data-unit=wei data-validate="required number gt0" data-value=20000000000></div>
            </div>
        </div>
        <div class=form-group>
            <label for=nonce>Nonce</label>
            <input class=form-control id=nonce data-validate-order-matters="required number gt0">
        </div>
        <button id=generate class="btn btn-block" data-i18n=send-nas/button/generate>Generate Transaction</button>
    </div>

    <!-- send -->
    <div id=transaction class="container transaction">
        <div class=row>
            <div class=col-6>
                <div class=form-group>
                    <label for=raw data-i18n=send-nas/raw>Raw Transaction</label>
                    <!-- TODO: TRX -->
                    <textarea class=form-control rows=8 id=raw disabled></textarea>
                </div>
                <div class=form-group>
                    <label for=signed data-i18n=send-nas/signed>Signed Transaction</label>
                    <textarea class=form-control rows=8 id=signed disabled></textarea>
                </div>
            </div>
            <div class="col-6 text-center">
                <label data-i18n=send-nas/signed_qr>Signed Transaction QR</label>
                <div id=addressqr></div>
            </div>
        </div>
        <button type=button id=send_transaction class="btn btn-block" data-toggle=modal data-target=#modal-confirm data-i18n=send-nas/send>Send </button>

        <!-- Transaction -->
        <div class="container transaction" id=receipt_div>
            <span data-i18n=contract/txhash></span>
            <i data-i18n=contract/clickToCheck></i>&darr;
            <a id=receipt></a>
            <div class=form-group>
                <label for=signed data-i18n=send-nas/receipt>receipt :</label>
                <textarea id=receipt_state rows=6 class=form-control disabled></textarea>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="fade modal" id=modal-confirm tabindex=-1 role=dialog aria-labelledby=exampleModalLabel aria-hidden=true>
        <div class=modal-dialog role=document>
            <div class=modal-content>
                <div class=modal-header>
                    <h5 class=modal-title id=exampleModalLabel data-i18n=send-nas/transfer_msg>transfer message :</h5>
                    <button type=button class=close data-dismiss=modal aria-label=Close>
                        <span aria-hidden=true>&times;</span>
                    </button>
                </div>
                <div class=modal-body>
                    <div>
                        <label data-i18n=send-nas/from-address>From Address</label>
                        <input type=text class=form-control id=for_addr disabled>
                    </div>
                    <div>
                        <label data-i18n=send-nas/to-address>To Address</label>
                        <input type=text class=form-control id=to_addr disabled>
                    </div>
                    <div>
                        <label for=amount data-i18n=send-nas/amount>Value / Amount to Send</label>
                        <div class=number-comma data-data-i18n=amount data-id=value data-unit=currency data-disabled></div>
                    </div>
                    <!-- <div class=data>
                        <label>data</label>
                        <input type=text class=data id=data disabled style="width: 100%;">
                    </div> -->
                </div>
                <div class=modal-footer>
                    <button class="btn btn-secondary" data-dismiss=modal data-i18n=send-nas/close>Close</button>
                    <button class="btn btn-primary s" data-dismiss=modal data-i18n=send-nas/check></button>
                </div>
            </div>
        </div>
    </div>

    <div class=footer></div>

    <script src=lib/jquery-3.3.1.min.js></script>
    <script src=lib/bootstrap-4.0.0-dist/js/bootstrap.bundle.min.js data-depends=jquery.slim></script>
    <script src=lib/bootbox.min.js data-depends="bootstrap jquery.slim"></script>
    <script src=lib/jquery.qrcode.min.js data-depends=jquery></script>
    <script src=lib/blockies.min.js></script>
    <script src=lib/nebulas.js></script>
    <script src=js/1-localSave.js></script>
    <script src=js/home.v1.js></script>
    <script src=js/i18n.js data-depends=jquery.slim></script>
    <script src=js/ui-block.js data-depends="bootbox blockies jquery.slim i18n.js nebulas.js"></script>
    <script>
        "use strict";

        var nebulas = require("nebulas"),
            Transaction = nebulas.Transaction,
            Utils = nebulas.Utils,
            Unit = nebulas.Unit,
            neb = new nebulas.Neb(),
            validateAll = uiBlock.validate(),
            gLastGenerateInfo = {},
            gAccount, gTx;

        neb.setRequest(new nebulas.HttpRequest(localSave.getItem("apiPrefix") || "https://testnet.nebulas.io/"));
        $("#generate").on("click", onClickGenerate);
        $("#modal-confirm .s").on("click", onClickModalConfirmS);
        $("#send_transaction").on("click", onClickSendTransaction);

        uiBlock.insert({
            footer: ".footer",
            header: ".header",
            iconAddress: ".icon-address",
            logoMain: ".logo-main",
            numberComma: ".number-comma",
            selectWalletFile: [".select-wallet-file", onUnlockFile]
        });

        function onCurrencyChanged() {
            updateBalance()
        }
        uiBlock.addCurrencyChangedListener(onCurrencyChanged);

        function onUnlockFile(swf, fileJson, account, password) {  //TODO: 对外函数不要用简称
            var address;
            try {
                account.fromKey(fileJson, password);
                address = account.getAddressString();
                gAccount = account;

                $(".icon-address.from input").val(address).trigger("input"); // gen icon from addr, needs trigger 'input' event if via set o.value
                $("#unlock").hide();
                $("#send").show();

                updateBalance();
            } catch (e) {
                // this catches e thrown by nebulas.js!account
                bootbox.dialog({
                    backdrop: true,
                    onEscape: true,
                    message: localSave.getItem("lang") == "en" ? e : "keystore 文件错误, 或者密码错误",
                    size: "large",
                    title: "Error"
                });
            }
        }

        function updateBalance() {
            if (!gAccount) {
                return;
            }
            var addr = gAccount.getAddressString();
            var currency = uiBlock.currency;
            var contractAddr = uiBlock.getContractAddr(uiBlock.currency);
            $("#balance").val("").trigger("input");
            if (currency == "NAS") {
                neb.api.getAccountState(addr)
                    .then(function (resp) {
                        if (currency != uiBlock.currency) {
                            return;
                        }
                        if (resp.error) {
                            throw new Error(resp.error);
                        }
                        var nas = Unit.fromBasic(resp.balance, "nas").toString(10);
                        $("#balance").val(nas).trigger("input"); // add comma & unit from value, needs trigger 'input' event if via set o.value
                        $("#nonce").val(parseInt(resp.nonce || 0) + 1);
                    })
                    .catch(function (e) {
                        if (currency != uiBlock.currency) {
                            return;
                        }
                        // this catches e thrown by nebulas.js!neb
                        bootbox.dialog({
                            backdrop: true,
                            onEscape: true,
                            message: i18n.apiErrorToText(e.message),
                            size: "large",
                            title: "Error"
                        });
                    });
            } else {
                var contract = {"function": "balanceOf", "args": "[\"" + addr + "\"]"};
                neb.api.call({"from": addr, "to": uiBlock.getContractAddr(uiBlock.currency), "gasLimit": 200000, "gasPrice":1000000, "value": 0, "contract": contract})
                    .then(function (resp) {
                        if (currency != uiBlock.currency) {
                            return;
                        }
                        if (resp.error) {
                            throw new Error(resp.error);
                        }
                        var b = resp.result.replace(/"/ig, "");
                        
                        var balance;

                        if(uiBlock.currency === "NAX") {
                            balance = Unit.fromBasic(b, "gwei").toString();
                        } else {
                            balance = Unit.fromBasic(b, "nas").toString(10);
                        }
                        
                        $("#balance").val(balance).trigger("input"); // add comma & unit from value, needs trigger 'input' event if via set o.value
                    })
                    .catch(function (e) {
                        if (currency != uiBlock.currency) {
                            return;
                        }
                        // this catches e thrown by nebulas.js!neb
                        bootbox.dialog({
                            backdrop: true,
                            onEscape: true,
                            message: i18n.apiErrorToText(e.message),
                            size: "large",
                            title: "Error"
                        });
                    });

                neb.api.getAccountState(addr)
                    .then(function (resp) {
                        if (!resp.error) {
                            $("#nonce").val(parseInt(resp.nonce || 0) + 1);
                        }
                    })
                    .catch(function (e) {
                    });
            }
        }

        function onClickGenerate() {
            var fromAddress, toAddress, balance, amount, gaslimit, gasprice, nonce, bnAmount;

            if (validateAll()) {
                fromAddress = $(".icon-address.from input").val();
                toAddress = $(".icon-address.to input").val();
                balance = $("#balance").val();
                amount = $("#amount").val();
                gaslimit = $("#limit").val();
                gasprice = $("#price").val();
                nonce = $("#nonce").val();

                if (gLastGenerateInfo.fromAddress != fromAddress ||
                    gLastGenerateInfo.toAddress != toAddress ||
                    gLastGenerateInfo.balance != balance ||
                    gLastGenerateInfo.amount != amount ||
                    gLastGenerateInfo.gaslimit != gaslimit ||
                    gLastGenerateInfo.gasprice != gasprice ||
                    gLastGenerateInfo.nonce != nonce) try {  //TODO: 加括号
                        var tmp = Unit.fromBasic(Utils.toBigNumber(gaslimit)
                            .times(Utils.toBigNumber(gasprice)), "nas");

                        if (Utils.toBigNumber(balance).lt(Utils.toBigNumber(amount).plus(tmp))) //TODO: 加括号； tmp-->max gas used
                            if (Utils.toBigNumber(balance).lt(tmp))
                                bnAmount = Utils.toBigNumber(0); //TODO: 逻辑是否必须有
                            else
                                bnAmount = Utils.toBigNumber(balance).minus(Utils.toBigNumber(tmp));

                        var a = amount.split(".");
                        var amountValid = a.length == 1 || a[1].length <= 18;
                        if (uiBlock.currency == "NAS") {
                            if (!amountValid) throw new Error("Invalid value! The minimum unit is wei (1^-18nas) ");
                            gTx = new Transaction(parseInt(localSave.getItem("chainId")), gAccount, toAddress, Unit.nasToBasic(Utils.toBigNumber(amount)), parseInt(nonce), gasprice, gaslimit);
                        } else {
                            if (!amountValid) throw new Error("Invalid value! The minimum unit is wei (1^-18" + uiBlock.currency.toLowerCase() + ") ");

                            var transfer_amount;
                            if(uiBlock.currency === "NAX") {
                                transfer_amount = Unit.toBasic(Utils.toBigNumber(amount), "gwei").toString();
                            } else {
                                transfer_amount = Unit.nasToBasic(Utils.toBigNumber(amount)).toString(10);
                            }

                            var contract = {"source": "", "sourceType": "js", "function": "transfer", "args": "[\"" + toAddress + "\", \"" + transfer_amount + "\"]", "binary": "", "type": "call"};
                            gTx = new Transaction(parseInt(localSave.getItem("chainId")), gAccount, uiBlock.getContractAddr(uiBlock.currency), Unit.nasToBasic(Utils.toBigNumber("0")), parseInt(nonce), gasprice, gaslimit, contract);
                        }
                        gTx.signTransaction();

                        $("#raw").val(gTx.toString());
                        $("#signed").val(gTx.toProtoString());

                        $("<div id=addressqr></div>")
                            .qrcode(gTx.toProtoString())
                            .replaceAll('#addressqr');

                        $("#transaction").show();

                        gLastGenerateInfo.fromAddress = fromAddress;
                        gLastGenerateInfo.toAddress = toAddress;
                        gLastGenerateInfo.balance = balance;
                        gLastGenerateInfo.amount = amount;
                        gLastGenerateInfo.gaslimit = gaslimit;
                        gLastGenerateInfo.gasprice = gasprice;
                        gLastGenerateInfo.nonce = nonce;
                    } catch (e) {
                        bootbox.dialog({
                            backdrop: true,
                            onEscape: true,
                            message: e,
                            size: "large",
                            title: "Error"
                        });
                    }
            }
        }

        function onClickSendTransaction() {
            $("#for_addr").val($(".icon-address.from input").val());
            $("#to_addr").val($(".icon-address.to input").val());
            $("#value").val($("#amount").val()).trigger("input");
        }

        function onClickModalConfirmS() {
            var mTxHash;

            gTx && neb.api.sendRawTransaction(gTx.toProtoString()) //TODO: GTX为空是 抛异常
                .then(function (resp) {
                    // console.log("sendRawTransaction resp: " + JSON.stringify(resp));
                    mTxHash = resp.txhash;
                    return neb.api.getTransactionReceipt(mTxHash);
                }).then(function (resp) {
                    $("#receipt").text(mTxHash).prop("href", "check.html?" + mTxHash);
                    $("#receipt_state").val(JSON.stringify(resp));
                    $("#receipt_div").show();

                    // TODO: 重新点击需要reset页面状态，清理setTimeout    （ 是否需要 ，如果需要的话给用户认知 ）
                    setTimeout(function () {
                        neb.api.getAccountState($(".icon-address.from input").val())
                            .then(function (resp) {
                                // console.log("getAccountState resp: " + JSON.stringify(resp));
                                var balanceNas = Unit.fromBasic(resp.balance, "nas").toString(10);
                                $("#balance").val(balanceNas);
                                $("#nonce").val(resp.nonce);
                            }).catch(function (err) {
                                // TODO error
                            });
                    }, 60 * 1000);
                }).catch(function (o) {
                    bootbox.dialog({
                        backdrop: true,
                        onEscape: true,
                        message: i18n.apiErrorToText(o.message),
                        size: "large",
                        title: "Error"
                    });
                });
        }
    </script>
</body>
</html>
